package bootstrap

import (
	"context"
	"fmt"
	log "github.com/sirupsen/logrus"
	"go.uber.org/zap"
	"litter-api/app/util/pool"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

type Boot struct {
	Server *http.Server
}

func New(srv *http.Server) *Boot {
	return &Boot{
		Server: srv,
	}
}

func (b *Boot) InitSignal() {
	sig := make(chan os.Signal)
	// 监听信号
	signal.Notify(sig, os.Interrupt, syscall.SIGHUP, syscall.SIGTERM)
	//ctx, cancel := context.WithCancel(context.Background())
	exitCh := make(chan int)

	go func() {
		select {
		case s := <-sig:
			b.ExitFunc()
			fmt.Println("捕捉到信号:", s)
			goto ExitProcess
		}
	ExitProcess:
		log.Println("Exit Service")
		exitCh <- 0
	}()
	code := <-exitCh
	os.Exit(code)
}

// ExitFunc Close 关闭服务
func (b *Boot) ExitFunc() {

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	if err := b.Server.Shutdown(ctx); err != nil {
		log.Fatal("Server Shutdown Err:", err)
	}

	//关闭数据库链接
	rd, err := pool.DbR.DB()
	if err != nil {
		log.Fatal("read mysql close err", zap.Error(err))
	}
	defer rd.Close()
	wd, err := pool.DbW.DB()
	if err != nil {
		log.Fatal("write mysql close err", zap.Error(err))
	}
	defer wd.Close()

	//close redis
	//defer pool.Redis.Close()

	select {
	case <-ctx.Done():
		log.Print("timeout of 2 seconds.")
	}
}
